package engine.newUi
{
	import engine.control.Base64;
	import engine.control.loading.MultLoader;
	import engine.data.BindManage;
	import engine.data.ModelLocator;
	import engine.data.ResPath;
	import engine.net.datatype.WString;
	import engine.net.event.CustomMsgEvent;
	import engine.net.messages.CustomToClientFlag;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.SystemSender;
	import engine.ui.lite.BaseUI;
	import engine.util.FilterUtil;
	
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	import flash.system.ApplicationDomain;
	import flash.utils.ByteArray;
	import flash.utils.getTimer;
	
	import newx.StageInfo;
	import newx.com.config.StaticIni;
	import newx.com.control.NxClip;
	import newx.com.control.window.NxWindowEvent;

	/**
	 * 
	 * @author yangcg
	 * 
	 */
	public class AdventureLogic
	{
		public static  var _self:AdventureLogic ; 
		public static function getInstance():AdventureLogic
		{
			if(_self==null)
			{
				_self = new AdventureLogic(); 	
			}
			return _self ; 
		}
		private var _model:ModelLocator; 
		public var _ui:AdventureUI; 
		private var _bingManager:BindManage;
		private var _pageIndex:uint; 
		private var _pageCount:int  = 0;
		/****每页显示多少个**/
		private var _ItemCount:uint = 0  ; 
		/***界面背景**/
		private var _mcBack:MovieClip  ; 
		/**每一张任务ID的配置**/
		private var _obj:Object ; 
//		/**奇遇任务名字****/
//		private var nameMC:MovieClip;
		/***获取你触发的奇遇页数***/
		private var _getPage:Boolean=true;  
		/**自动弹2级界面***/
		private var _isOk:Boolean = false ;
		/**触发条件的ID**/
		private var configID:int  = 0 ; 
 		/**触发条件的位置**/
		private var advenLocality:int = 0 ; 
		/***所有奇遇条件**/
		private var _strArr:String  ="" ; 
		/*****/
		private var _isOK:Boolean =false; 
		public function AdventureLogic()
		{
			
		}
		public function init():void
		{
			_ui = AdventureUI.getInstance();
			_model= ModelLocator.getInstance();
			_bingManager = BindManage.getInstance(); 
			
			//SERVER_CUSTOMMSG_ADVENTURE_CONDTION_CHECKED
			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_ADVENTURE_CONDTION_CHECKED),getEffect);
			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_ADVENTURE_INFO),getInfo);
			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_EVERYDAY_ADVENTURE),getEveryday);
			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_REQUEST_ADVENTURE_CONFIG),getAllStr);
			_obj =StaticIni.getIniObj("AdventurePageConfig");
			_pageCount = _obj["countpage"] ; 
			if(_pageCount<=1)
			{
				_ui.right_btn.visible = false ; 
				_ui.left_btn.visible = false ; 
			}else
			{
				_ui.right_btn.visible = true ; 
				_ui.left_btn.visible = true ; 
			}
			_ui.label_2.wordWrap = true ; 
		}
		public function BeforeShow():void
		{
//			trace(getTimer()+"显示界面时间");
			if(_ui.created==true)return  ;
			if(_isOK==false)
			{
//				trace(getTimer()+"开始加载奇遇配置文件");
				SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_DOWNLOAD_ADVENTURE_CONFIG);
			}
			//
			_ui.btn_1.label = StaticIni.getSwfLangStr("UIStr_1000418"); 
			_ui.btn_1 .visible =false ; 
			_pageIndex=1 ; 
			_ItemCount = _ui.itemGroup.col * _ui.itemGroup.row ;
			inteGroup();
//			ShowBack();
			addListener();
			getPageIndex();
			
		}
		/**
		 * 关闭界面要回收的东西 
		 * 
		 */		
		public function AfterHide():void
		{
			_ItemCount = 0 ; 
			var i :uint = 0; 
			for( i ; i<_ItemCount ;i++)
			{
				var itemMC:MovieClip = _ui.itemGroup.getItemByIndex(i) ; 
				itemMC["data"] = 0 ; 
				itemMC["image"].source = "";
				itemMC["configID"]	 = 0 ; 
			}
			removeListener();
			ActivitesGroupLogic.getInstance().removeEffect(28);
		}
		/**
		 * 设置监听 
		 * 
		 */		
		private function addListener():void
		{
			_ui.left_btn.addEventListener(MouseEvent.CLICK,leftClickHandler);
			_ui.right_btn.addEventListener(MouseEvent.CLICK,rightClickHandler);
			_ui.windowBG.addEventListener(NxWindowEvent.WINDOW_CLOSE,closeClickHandler);
			
			_ui.itemGroup.addItemsEvent(MouseEvent.MOUSE_OVER , overHanlder); 
			_ui.itemGroup.addItemsEvent(MouseEvent.MOUSE_OUT,outHandler);
			_ui.itemGroup.addItemsEvent(MouseEvent.CLICK,clickHandler);
			_ui.btn_1.addEventListener(MouseEvent.CLICK, btnClickHandler); 
			


		}
		/**
		 *移除监听事件 
		 * 
		 */		
		private function removeListener():void
		{
			_ui.left_btn.removeEventListener(MouseEvent.CLICK,leftClickHandler);
			_ui.right_btn.removeEventListener(MouseEvent.CLICK,rightClickHandler);
			_ui.windowBG.removeEventListener(NxWindowEvent.WINDOW_CLOSE,closeClickHandler);
			
			_ui.itemGroup.removeItemsEvent(MouseEvent.MOUSE_OVER , overHanlder);
			_ui.itemGroup.removeItemsEvent(MouseEvent.MOUSE_OUT,outHandler);
			_ui.itemGroup.removeItemsEvent(MouseEvent.CLICK,clickHandler);
		}
		private function leftClickHandler(e:MouseEvent):void
		{
			
			if(_pageIndex>1)
			{
				_pageIndex--;
				if(_pageIndex<=1)
				{
					_ui.left_btn.enabled = false ;
				}

			}
			if(_pageIndex<_pageCount)
			{
				_ui.right_btn.enabled= true ;
			}
			_ui.label_count.htmlText  =StaticIni.getSwfLangStr("UIString_" +_pageIndex); 
			getTaskID(_pageIndex);
		}
		private function rightClickHandler(e:MouseEvent):void
		{
			
			if(_pageIndex<_pageCount)
			{
				_pageIndex++;
				if(_pageIndex>=_pageCount)
				{
					_ui.right_btn.enabled = false ;
				}

			}
			if(_pageIndex>1)
			{
				_ui.left_btn.enabled= true ;
			}
			_ui.label_count.htmlText  =StaticIni.getSwfLangStr("UIString_" +_pageIndex); 
			getTaskID(_pageIndex);
		}
		private function closeClickHandler(e:NxWindowEvent):void
		{
			_ui.showOrHide();
		}
		/**
		 * 鼠标移到可选状态
		 * 
		 */
		private function overHanlder(e:MouseEvent):void
		{
			var itemMC:MovieClip = e.currentTarget as MovieClip ; 
			if(itemMC["data"]==0||itemMC["data"]==16)
			{
				
			}else 
			{
				itemMC.gotoAndStop(2);
			}
		}
		/**
		 *  鼠标移开
		 */
		private function outHandler(e:MouseEvent):void
		{
			var itemMC:MovieClip = e.currentTarget as MovieClip ; 
			itemMC.gotoAndStop(1) ;
		}
		/**
		 *clickHandler 单击奇遇任务 
		 */		
		private function clickHandler(e:MouseEvent):void
		{
			var itemMC:MovieClip = e.currentTarget as MovieClip ; 
			if(itemMC["data"]==0 )
			{
				
			}else
			{
				AdventureTermLogic.getInstance().nameMc = getNameImage(itemMC["configID"]) as MovieClip  ; 
				AdventureTermLogic.getInstance().configID = itemMC["configID"];
				AdventureTermUI.getInstance().showOrHide();
			}
			
		}
		/**
		 * 
		 * @param e 初始化 奇遇列表
		 *  0 代表 不亮-------1就是亮
		 */
		private function inteGroup():void
		{
			var i :uint = 0; 
			for( i ; i<_ItemCount ;i++)
			{
				var itemMC:MovieClip = _ui.itemGroup.getItemByIndex(i) ; 
				var image:NxClip  = new NxClip(); 
				itemMC["pic"].addChild(image) ; 
				if(!itemMC["image"])
				itemMC["image"]  = image ; 
				itemMC["data"]  = 0 ; 
				itemMC.gotoAndStop(1);
				itemMC.visible = false ; 
			}
		}
		/**
		 * 服务器传过来的消息
		 * @param e
		 * 
		 */		 
		private function getInfo(e:CustomMsgEvent):void
		{
//			trace(getTimer()+"接受到全服奇遇");
			var count:uint = e.pList[0];  
			if(count==0||e.pList.length<3)
			{
				_ui.left_btn.visible =false;
				_ui.right_btn .visible = false; 
				return ; 
			}
			
			var i :uint =0 ; 
			var  arr:Array= []; 
			for(i ; i <count ; i++)
			{
				arr.push(e.pList[1+i*2]);
				arr.push(e.pList[2+i*2]);
			}
			if((arr.length/2)<=int(_obj["maxnum"]))
			{
//				trace(getTimer()+"接受指定页奇遇时间");
				showItemGroup(arr) ; 
			}else  if ((arr.length/2)>int(_obj["maxnum"]))
			{
//				trace(getTimer()+"处理全服奇遇条件");
				showPage(arr);
			}
			
		}
		/**
		 * 
		 * @param arr
		 * 筛选奇遇触发页数
		 */		
		private function showPage(arr:Array):void
		{
			_getPage= true ; 
			var i :uint = 0 ; 
			for(i ; i<arr.length/2 ;i++)
			{
				if(arr[i*2+1]==4&&_getPage)
				{
					_getPage =false ; 
					 _pageIndex= i/12 +1 ; 
				}
			}
//			trace(getTimer()+"处理完全服奇遇知道翻到第几页");
//			trace(getTimer()+"申请当前页的奇遇和每日奇遇"+_pageIndex);
			getTaskID(_pageIndex);
			_ui.label_count.htmlText  =StaticIni.getSwfLangStr("UIString_" +_pageIndex)  ; 
			BtnState();
		}
		/**
		 * 
		 * @param arr
		 * 翻页按钮状态
		 */
		private function BtnState():void
		{
			if(_pageIndex>=_pageCount)
			{
				_ui.right_btn.enabled =false ; 
				_ui.left_btn.enabled = true ; 
			}else if(_pageIndex<=1)
			{
				_ui.right_btn.enabled =true  ; 
				_ui.left_btn.enabled = false ; 
			}else
			{
				_ui.right_btn.enabled =true  ; 
				_ui.left_btn.enabled = true  ; 
			}
		}
		/**
		 *显示奇遇列表 
		 */		
		private function showItemGroup(arr:Array):void
		{
			var i :uint = 0; 
			for( i ; i<_ItemCount ;i++)
			{
				
				var itemMC:MovieClip = _ui.itemGroup.getItemByIndex(i) ; 
				if(i<int(arr.length/2))
				{
					itemMC.visible = true ; 
					var confingID:int = arr[i*2];
					itemMC["configID"]	=  confingID ; 
					itemMC["data"]	= arr[1+i*2] ; 
					
					var name:MovieClip = getNameImage(confingID) as MovieClip ; 
					itemMC["image"].source = ""; 
					itemMC["image"].source =name ; 
					
					if(itemMC["data"]==0||itemMC["data"]==16)
					{
						itemMC.filters = [FilterUtil.GrayColorFilter] ;
						if(arr[1+i*2] ==0)
						{
							//变成问好
							itemMC["image"].source = "" ; 
							itemMC["image"].source =getNameImage(772000) as MovieClip ;
						}
						
					}else 
					{
						
						itemMC.filters = [] ;
					}
				}
				else
				{
					itemMC.visible = false ; 
				}
			}
			if(_isOk)
			{
				AdventureTermLogic.getInstance().nameMc = getNameImage(configID) as MovieClip  ; 
				AdventureTermLogic.getInstance().configID =configID; 
				AdventureTermUI.getInstance().showOrHide();
				_isOk =false ; 
			}
//			trace(getTimer()+"显示结束时间");
		}
		/**
		 * 
		 */
		private function getNameImage(str:int):DisplayObject
		{
			var domain:ApplicationDomain= app
			if(domain.hasDefinition("AdventurePic_" +str.toString()))
			{
				var cls:Class = domain.getDefinition("AdventurePic_" +str.toString()) as Class ; 
				return new cls ; 
			}else
			{
				return null ; 
			}
		}
		/**
		 *加载背景图片 
		 */	
		public function ShowBack():void
		{
//			trace(getTimer()+"开始加载资源");
//			_ui.imaback.source =ResPath.PNG+"qiyu0bg.png" ; 
			MultLoader.getInstance().load([ResPath.SWF + "AdventureName.swf"],true,createScene);
		}
		private var app:ApplicationDomain;
		private function createScene():void
		{
			var nameMC:MovieClip  =  MultLoader.getInstance().getSourceByUrl(StageInfo.swfResPath + "AdventureName.swf") ;
			app=nameMC.loaderInfo.applicationDomain;
			_ui.imaback.source  =  getNameImage(882000) as MovieClip;
//			getTaskID(_pageIndex);
//			trace(getTimer()+"加载资源完成");
			_ui.showUI();
			
//			if(_isOk)
//			{
//				AdventureTermLogic.getInstance().nameMc = getNameImage(configID) as MovieClip  ; 
//				AdventureTermLogic.getInstance().configID =configID; 
//				AdventureTermUI.getInstance().showOrHide();
//				_isOk =false ; 
//			}
			
		}
		/**
		 *查询全副奇遇状态 
		 * 如果有奇遇饱足条件就跳到那一章节
		 */		
		private function getPageIndex():void
		{
//			trace(getTimer()+"请求全服奇遇");
			var str:String = _obj["all"] ; 
			var arr:Array  = str.split(","); 
			arr.unshift(arr.length);
			SystemSender.getInstance().CustomMsgEx(CustomToServerFlag.CLIENT_CUSTOMMSG_OPEN_ADVENTURE_UI,arr);

		}
		/**
		 * 
		 * @param value当前页数
		 * 用当前页数获取当前页数的奇遇状态
		 * 
		 */		
		private function getTaskID(value:int ):void
		{
			var i :uint = 0; 
			for( i ; i<_ItemCount ;i++)
			{
				var itemMC:MovieClip = _ui.itemGroup.getItemByIndex(i) ; 
				itemMC["data"] = 0 ; 
				itemMC["image"].source = "";
				itemMC["configID"]	 = 0 ; 
			}
			var str:String = _obj["page"+value] ; 
			var arr:Array  = str.split(","); 
			arr.unshift(arr.length);
//			trace(getTimer()+"发送申请完当前页的奇遇和每日奇遇"+_pageIndex);
			SystemSender.getInstance().CustomMsgEx(CustomToServerFlag.CLIENT_CUSTOMMSG_OPEN_ADVENTURE_UI,arr);
			SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_EVERYDAY_ADVENTURE);
//			trace(getTimer()+"申请完当前页的奇遇和每日奇遇"+_pageIndex);
		}
		/**
		 *每日奇遇
		 * 按钮 
		 */		
		private function btnClickHandler(e:MouseEvent):void
		{
//			var mc:MovieClip  = e.currentTarget as MovieClip ; 
		
			AdventureTermLogic.getInstance().nameMc = getNameImage(int(_ui.btn_1.data.GetProperties("configID"))) as MovieClip  ; 
			AdventureTermLogic.getInstance().configID = _ui.btn_1.data.GetProperties("configID");
			AdventureTermUI.getInstance().showOrHide();
		}
		/**
		 *获取每日信息的 
		 */	
		private function getEveryday(e:CustomMsgEvent):void
		{
			if(e.pList[0]==0 ||e.pList.length==0)return ; 
			_ui.btn_1.visible = true ; 
			_ui.btn_1.data.HandleProperties("configID", e.pList[0]);
			_ui.label_2.htmlText  =AdventureTermLogic.getInstance().getStr("AdventureTips_" + e.pList[0].toString());
//				StaticIni.getSwfLangStr() ; 
			
		}
		/**
		 *  获取条件
		 */
		private function getEffect(e:CustomMsgEvent):void
		{
			_isOk = true ; 
			ActivitesGroupLogic.getInstance().addEffect(28);
			advenLocality	 = e.pList[1]; 
			configID=e.pList[0] ; 
		}
		/**
		 * 加载奇遇所有 配置文件
		 */
		private function getAllStr(e:CustomMsgEvent):void
		{
		
			var decoded:ByteArray = Base64.Decode(e.pList[0]); 
			decoded.uncompress();
			
			_strArr = decoded.readUTFBytes(decoded.bytesAvailable);
			_isOK = true  ; 
//			trace(getTimer()+"加载奇遇配置文件完成时间");
		}
		/**
		 * 
		 */		
		public function get strArr():String
		{
			return _strArr ; 
		}
	}
}